<?php
namespace app\houtai\controller;
/**
 *  @file : BaseController.php
 *  @brief: 后台操作基础类
 */
class BaseController extends \think\Controller {

  protected $pageSize    = 20;
  protected $pageCurrent = 1;
  protected $pageMaxSize = 200;
  protected $orderField  = '';
  protected $orderDirection = 'ASC';
  protected $auid = 0;

  // 所有继承该控制器的Action都需要执行
  protected $beforeActionList = ['checkHtAuth', 'checkHtRBAC'];
  
  // 初始化
  protected function _initialize() {

  }
  /**
   *  @brief  : 检测后台是否已登录
   *  @return : none|redirect
   *  @details: 如果已经登录则继续向下执行到控制器Action, 否则重定向到登录页面
   */
  protected function checkHtAuth() {
    $ref = $this->request->url(true); // 当前请求完整URL, 包括QUERY_STRING
    $name = config('auth.session');
    $auid = session($name);   // 取值（当前作用域）
    if ($auid <= 0) { // 判断是否登陆
      session(null);
      $url = config('auth.getway');
      return $this->redirect($url);
    }
    $this->auid = $auid;
    $this->_initPageVars(); // 初始化页面变量
  }
  /**
   *  @brief  : 检测是否有访问权限
   *  @return : none|abort
   *  @detail : 
   */
  protected function checkHtRBAC() {

    $ref = $this->request->url(true); // 当前请求完整URL, 包括QUERY_STRING
    $path = strtolower($this->request->path());
    $path = in_array($path, ['index', '/']) ? 'index/index' : $path;

    $rbac = table('Ky_Admin a', 'rydb.websms')->field([
      'b.NodeID', 'c.IsDisabled', 'c.IsDelete', 'b.State'
    ])
    ->join('Ky_AdminRoleAction b', 'b.RoleID = a.RoleID', 'LEFT')
    ->join('Ky_AdminAction c', 'c.NavId = b.NodeID', 'LEFT')
    ->where(['a.AdminId' => $this->auid, 'c.LinkUrl' => $path])
    ->find();
    if (empty($rbac) || $rbac['State'] == 0) {
      return $this->RBAC_EXCEPTION(1026, "没有权限[{$this->auid}][{$path}]");
    }
    if ($rbac['IsDelete'] == 1 || $rbac['IsDisabled'] == 1) {
      return $this->RBAC_EXCEPTION(1027, "无效地址[{$this->auid}][{$path}]");
    }
  }
  
  private function RBAC_EXCEPTION($errno, $error) {
    $isPost = $this->request->isPost();
    $isAjax = $this->request->isAjax();
    if ($isPost || $isAjax) {
      return result([], $errno, $error);
    } else {
      return abort($errno, $error);
    }
  }
  /**
   *  @brief  : 获取当前角色限制渠道
   *  @return : array
   *  @detail : 如果角色无设置限制渠道, 则所有渠道可视
   */
  protected function GetAdminChannel() {
    static $_cahce = [];
    if (empty($_cahce)) {
      $arlc = table('Ky_Admin a', "rydb.websms")
              ->join('Ky_AdminRole b', 'b.ID = a.RoleID', 'LEFT')
              ->where('a.AdminId', $this->auid)
              ->value('b.LimitChannel');
      $arlc = empty($arlc) ? [] : explode(',', $arlc);
      $conds = ['State' => 1];
      if (!empty($arlc)) {
          $conds['ID'] = ['IN', $arlc];
      }
      $_cahce = table('ChannelConfig', 'rydb.basic')->where($conds)->column('ID,Name');
    }
    return $_cahce;
  }
    /**
     *  @brief  : 获取所有用户
     *  @return : array
     *  @detail : 进行实时匹配用户信息
     */

  protected  function GetUserInfo() {
        $list = [];
        if (empty($list)) {
            $rows = table('AccountsInfo', 'rydb.basic')->field([
                'UserID','GameID','RegisterIP','UserRight','PassPortID','GameLogonCount','LastLogonDate','LastLogonIP','RegisterDate','Sex','Compellation','AccountImgUrl','AccountsType','Accounts','NickName','RegisterMobile'
            ])->select();
            if (!empty($rows)) {
                foreach($rows as $row) {
                    $list[$row['UserID']] = $row;
                }
            }
        }
        return $list;
    }




  /**
   *  @brief : 过滤/初始化 查询页面所必须变量
   *  @return: Return_Description
   *  @detail: Details
   */
  private function _initPageVars() {
    $C = [
      'orderField'      => 'orderField',  //排序字段
      'orderDirection'  => 'orderDirection',   //排序方向 (DESC  ,  ASC)
      'pageSize'        => 'size',    //
      'pageCurrent'     => config('paginate.var_page'),  //当前页
    ];
    // 排序变量
    $this->orderField     = $this->request->param("{$C['orderField']}/s", '', 'trim,strtoupper');
    $this->orderDirection = $this->request->param("{$C['orderDirection']}/s", 'DESC', 'trim,strtoupper');
    $this->orderDirection = in_array($this->orderDirection, ['DESC', 'ASC']) ? $this->orderDirection : 'DESC';

    // 分页变量
    $pageSize     = $this->request->param("{$C['pageSize']}/d", 0);
    $pageCurrent  = $this->request->param("{$C['pageCurrent']}/d", 0);
    $this->pageSize = config('paginate.list_rows');
    if ($pageSize > $this->pageMaxSize) {
      $this->pageSize = $this->pageMaxSize;
    } else if ($pageSize > 0 && $pageSize <= $this->pageMaxSize) {
      $this->pageSize = $pageSize;
    } else {
      //
    }
    config('paginate.list_rows', $this->pageSize);  // TP paginator类中会用到
    $this->pageCurrent = $pageCurrent>0 ? $pageCurrent : $this->pageCurrent;
  }
  /**
   * 重置父类fetch方法, 强制输出为html, 因为BJUI中页片文件全都以Ajax方式请求
   */
  protected function fetch($template = '', $vars = [], $replace = [], $config = []) {
    // 页片文件中表单提交地址, 默认统一定义成当前查询页面;
    if (empty($vars['__ACTION__'])) {
      if (empty($this->view->__ACTION__)) {
        $__ACTION__ = parse_url($_SERVER['REQUEST_URI'])['path'];
      } else {
        $__ACTION__ = $this->view->__ACTION__;
      }
    } else {
      $__ACTION__ = $vars['__ACTION__'];
    }
    //////////////////////////////////////////////////////////////////////////
    $vars = array_merge($vars, [// 查询页面所必须变量赋值
      'pageSize'        => $this->pageSize,
      'pageCurrent'     => $this->pageCurrent,
      'orderField'      => $this->orderField,
      'orderDirection'  => $this->orderDirection,
      '__ACTION__'  => $__ACTION__,
    ]);
    $data = $this->view->fetch($template, $vars, $replace, $config);
    $resp = new \think\Response($data);
    return $resp;
  }
}
